
import { users } from './user'

// 生成更多测试消息的辅助函数
const generateMessages = (sessionId, count = 50) => {
    const messages = []
    const textMessages = [
        '你好', '最近怎么样？', '在忙什么呢？', '有空聊聊吗？', '今天天气不错',
        '工作顺利吗？', '周末有什么计划？', '最近看了什么好电影？', '推荐个好餐厅吧',
        '这个问题怎么解决？', '代码写得怎么样？', '项目进展如何？', '需要帮忙吗？',
        '晚上一起吃饭？', '明天见面聊？', '发个文件给你', '看看这个链接',
        '哈哈哈', '好的', '没问题', '收到', '谢谢', '不客气', '再见', '晚安'
    ]
    
    // 模拟当前用户的邮箱（假设是users[0]）
    const currentUserEmail = users[0].email
    
    for (let i = 1; i <= count; i++) {
        const isFromCurrentUser = i % 3 === 0 // 每3条消息中有1条来自当前用户
        const messageType = i % 10 === 0 ? 'image' : 'text' // 每10条消息有一条图片
        
        const message = {
            id: i.toString(),
            from_id: isFromCurrentUser ? currentUserEmail : users[parseInt(sessionId) % users.length].email,
            type: messageType,
            send_at: 1324567890 + i * 60 // 每条消息间隔1分钟
        }
        
        // 为自己发送的消息添加状态
        if (isFromCurrentUser) {
            // 模拟不同的消息状态：sent(已发送), read(已读)
            // 最近的消息更可能是已发送但未读，较早的消息更可能已读
            const isRecentMessage = i > count - 5 // 最后5条消息
            message.status = isRecentMessage && Math.random() > 0.3 ? 'sent' : 'read'
        }
        
        if (messageType === 'text') {
            message.text = textMessages[i % textMessages.length]
        } else {
            message.image = {
                id: `test_md5_value${i}`,
                path: users[parseInt(sessionId) % users.length].avatar
            }
        }
        
        messages.push(message)
    }
    
    return messages.reverse() // 最新消息在后面
}

export const StaticMessages = {
    "001": generateMessages("001", 50),
    "002": generateMessages("002", 45),
    "003": generateMessages("003", 60),
    "004": generateMessages("004", 35),
    "005": generateMessages("005", 25)
}
// 用户和会话id的映射
export const userSessionMap = {
    [users[0].email]: "001",
    [users[1].email]: "002",
    [users[2].email]: "003",
    [users[3].email]: "004",
    [users[4].email]: "005",
};

export const StaticSessions = [
    {
        id: "001",
        name: users[0].username,
        avatar: users[0].avatar,
        is_group: false,
        unread: 0,
        updated_at: 1324567890,
        is_pinned: false,
    },
    {
        id: "002",
        name: users[1].username,
        avatar: users[1].avatar,
        is_group: false,
        unread: 0,
        updated_at: 1324567890,
        is_pinned: false,
    },
    {
        id: "003",
        name: users[2].username,
        avatar: users[2].avatar,
        is_group: false,
        unread: 0,
        updated_at: 1324567890,
        is_pinned: false,
    },
    {
        id: "004",
        name: users[3].username,
        avatar: users[3].avatar,
        is_group: false,
        unread: 0,
        updated_at: 1324567890,
        is_pinned: false,
    },
    {
        id: "005",
        name: users[4].username,
        avatar: users[4].avatar,
        is_group: false,
        unread: 0,
        updated_at: 1324567890,
        is_pinned: false,
    }
]


export const getSessions = async (page, page_size) => {
    const start = (page - 1) * page_size;
    const end = start + page_size; 
    return {
        sessions: StaticSessions.slice(start, end),
        total: StaticSessions.length
    }
}

export const getSessionMessages = async (session_id, page, page_size) => {
    const start = (page - 1) * page_size;
    const end = start + page_size;
    return {
        messages: StaticMessages[session_id].slice(start, end),
        total: StaticMessages[session_id].length
    }
}

// 加载更多消息（基于最早消息ID）
export const loadMoreMessages = async (session_id, last_message_id, page_size = 10) => {
    const allMessages = StaticMessages[session_id] || []
    
    // 找到last_message_id在消息列表中的位置
    let startIndex = 0
    if (last_message_id) {
        const lastIndex = allMessages.findIndex(msg => msg.id === last_message_id)
        if (lastIndex !== -1) {
            startIndex = lastIndex + 1 // 从下一条消息开始
        }
    }
    
    // 获取更多消息
    const endIndex = Math.min(startIndex + page_size, allMessages.length)
    const messages = allMessages.slice(startIndex, endIndex)
    
    return {
        messages: messages,
        has_more: endIndex < allMessages.length,
        total: allMessages.length
    }
}

export const getFriends = async (ids) => {
    return {
        users: users.filter(f => ids.includes(f.id)),
        total: users.length
    }
}

// 会话成员映射 - 简单的映射关系
// 格式: sessionId -> [email1, email2]
export const sessionMembers = {
    "001": [users[0].email, users[1].email],
    "002": [users[0].email, users[2].email], 
    "003": [users[0].email, users[3].email],
    "004": [users[0].email, users[4].email],
    "005": [users[1].email, users[2].email]
}

// 根据两个用户邮箱查找或创建会话
export const findOrCreateSession = (email1, email2) => {
    // 生成一致的会话ID（邮箱排序）
    const sortedEmails = [email1, email2].sort()
    const sessionId = sortedEmails.join('_')
    
    // 查找现有会话
    for (const [existingSessionId, members] of Object.entries(sessionMembers)) {
        const sortedMembers = members.sort()
        if (sortedMembers[0] === sortedEmails[0] && sortedMembers[1] === sortedEmails[1]) {
            return {
                sessionId: existingSessionId,
                isNew: false
            }
        }
    }
    
    // 创建新会话
    const newSessionId = Object.keys(sessionMembers).length.toString().padStart(3, '0')
    sessionMembers[newSessionId] = sortedEmails
    
    return {
        sessionId: newSessionId,
        isNew: true
    }
}
